package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ServiceItemServiceImpl serviceItemService;

    @Autowired
    private TaskService taskService;

    @Override
    public CarPackageAudit get(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        return carPackageAudit;
    }

    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public void update(CarPackageAudit carPackageAudit) {

    }

    @Override
    public void deleteBatch(Long id, Integer statusCancel) {

    }

    @Override
    public List<CarPackageAudit> list() {
        return null;
    }

    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public void updateInstanceId(CarPackageAudit audit) {
        carPackageAuditMapper.changeAudit(audit);
    }

    @Override
    public InputStream getProcessImageByAuditId(Long id) {
        //根据id查询审核对象,判断审核对象的状态
        CarPackageAudit audit = this.get(id);
        System.out.println(audit);
        //审核对象关联的流程实例id
        List<String> highLightedActivities = null;
        if(audit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)){
            //获取流程实例对象
            //如果处于审核中，需要高目前运行节点
            //获取运行的任务
            //根据流程实例id获取到目前活动节点
            highLightedActivities = runtimeService.getActiveActivityIds(audit.getInstanceId());
        }else {
            //如果是审核通过 拒绝 不需要高任何节点
            highLightedActivities = new ArrayList<>();
        }
        //根据bpmnInfoId查询bpmnIn对象，对象中存储流程定义的id
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        //获取 Bpmn 模型
        BpmnModel model = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        //DefaultProcessDiagramGenerator(默认流程图生成器)
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
        return generator.generateDiagram(model, highLightedActivities, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        carPackageAuditMapper.changeAuditStatus(id,CarPackageAudit.STATUS_CANCEL);
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"撤销审核");
    }

    @Override
    @Transactional
    //审核流程步骤
    public void audit(Long id, int auditStatus, String info) {
        CarPackageAudit carPackageAudit = this.get(id);
        //判断状态
        if(carPackageAudit==null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("只有处于审核状态的记录才能进行审核操作");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            info = userName+"【同意】,批注意见:"+info;
        }else {
            info = userName+"【拒绝】,批注意见:"+info;
        }
        carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+info);
        Task task = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();

        taskService.setVariable(task.getId(),"auditStatus",auditStatus);

        taskService.addComment(task.getId(),carPackageAudit.getInstanceId(),info);

        taskService.complete(task.getId());

        //获取下一个节点
        Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();

        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            if(nextTask!=null){
                //财务审核
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));

                carPackageAudit.setAuditTime(new Date());
            }else {
                //审核通过
                serviceItemService.updateAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);

                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            }
        }else {
                //审核拒绝
            serviceItemService.updateAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);

            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            }
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }
}
